<template>
  <div>
    <!-- right-list-box start -->
    <div class="right-list-box" :class="{'unlock-list-active':!isListLocked}">
      <div class="top">
        <div>
          <el-checkbox v-model="allChecked" @change="changeAllCheck" :disabled="isListLocked"
                       :indeterminate="isIndeterminate">全选
          </el-checkbox>
          <i @click="changeListLocked" :class="[isListLocked?'icon-locked':'icon-lock']"></i>
        </div>
        <div class="menu">
          <div class="border-box">
                        <span :class="{'active':isMulti}" @click="changeMulit(true)" title="大图视图">
                            <i :class="[isMulti?'icon-multi':'icon-multi1']"></i>
                        </span>
            <span :class="{'active':!isMulti}" @click="changeMulit(false)" title="列表视图">
                            <i :class="[!isMulti?'icon-list':'icon-list1']"></i>
                        </span>
          </div>
          <i class="icon-record" @click="addItem('record')" title="录制漫游"></i>
          <i class="icon-draw" @click="addItem('draw')" title="绘制漫游"></i>
          <i class="icon-delete1" @click="deleteList" title="删除"></i>
<!--          <span class="border-daoru" @click="daoru" title="导入漫游">-->
<!--                        <i class="dao-ru"></i>-->
<!--                    </span>-->
<!--          <span class="border-daochu" @click="daochu" title="导出漫游">-->
<!--                        <i class="dao-chu"></i>-->
<!--                    </span>-->
        </div>
      </div>

      <transition-group :name="isListLocked?'':'drag'" class="btm ag-scrollbar">
        <!-- 大图 picture-item start -->
        <template v-if="isMulti">
          <div class="picture-item" v-for="(record, index) in roamList" :key="record.id"
               :draggable="!isListLocked" @dragstart="dragstart(record)" @dragenter="dragenter(record)"
               @dragend="dragend(record)">
            <el-checkbox v-model="record.checked" @change="changeCheck"></el-checkbox>
            <div class="draw-mark" v-if="record.json.roamType !== 'record'">
              <i class="icon-draw-mark"></i>
            </div>
            <div @click="playItem(record, index)">
              <i class="play-icon iconPlayer" v-show="record.id == curItem.id"/>
              <i class="pause-icon iconPlayer" v-show="record.id != curItem.id"/>
            </div>
            <img :src="record.json.code"/>
            <el-tooltip v-if="record.name.length > 10" :content="record.name" placement="bottom-start" effect="dark">
              <p class="name">{{ record.name }}</p>
            </el-tooltip>
            <p class="name" v-else>{{ record.name }}</p>
            <el-tooltip>
              <template slot="content"> 编辑</template>
              <span class="ibox edit">
                                <i class="agcim-edit_outlined iconfont icon" @click.stop="editItem(record)"></i>
                            </span>
            </el-tooltip>
            <el-tooltip>
              <template slot="content"> 删除</template>
              <span class="ibox delete">
                                <el-popconfirm title="是否确认要删除这个漫游？" @confirm="deleteItem(record.id)"
                                               confirm-button-text="确认" cancel-button-text="取消">
                                    <i slot="reference" class="agcim-trash iconfont icon"></i>
                                </el-popconfirm>
                            </span>
            </el-tooltip>
          </div>
        </template>
        <!-- 大图 picture-item end -->
        <!-- 缩略图 thumb-item start -->
        <template v-if="!isMulti">
          <div class="thumb-item" v-for="(record, index) in roamList" :key="record.id"
               :draggable="!isListLocked" @dragstart="dragstart(record)" @dragenter="dragenter(record)"
               @dragend="dragend(record)">
            <div>
              <el-checkbox v-model="record.checked" @change="changeCheck"></el-checkbox>
              <span class="record-index">{{ index + 1 }}</span>
              <img :src="record.json.code"/>
              <el-tooltip v-if="record.name.length > 10" :content="record.name" placement="bottom-start" effect="dark">
                <span class="record-name">{{ record.name }}</span>
              </el-tooltip>
              <span class="record-name" v-else>{{ record.name }}</span>
            </div>
            <div class="rt">
                            <span @click="playItem(record, index)">
                                <i class="icon-play" v-show="record.id == curItem.id"/>
                                <i class="icon-pause" v-show="record.id != curItem.id"/>
                            </span>
              <span><i class="icon-edit" @click.stop="editItem(record)"></i></span>
              <el-tooltip>
                <template slot="content"> 删除</template>
                <span class="ibox delete">
                                    <el-popconfirm title="是否确认要删除这个漫游？" @confirm="deleteItem(record.id)"
                                                   confirm-button-text="确认" cancel-button-text="取消">
                                        <i slot="reference" class="icon-delete"></i>
                                    </el-popconfirm>
                                </span>
              </el-tooltip>
            </div>
          </div>
        </template>
        <!-- 缩略图 thumb-item end -->
      </transition-group>
      <div class="empty" v-if="roamList.length==0">暂无数据</div>
    </div>
    <!-- right-list-box end -->
    <!-- 录制 -->
    <addRecordPanel :groupList="groupList" @updateList="updateList" ref="recordBox"></addRecordPanel>
    <!-- 绘制 -->
    <addOrEditDrawPanel :groupList="groupList" @updateList="updateList" ref="drawBox"></addOrEditDrawPanel>
    <!-- 导入漫游 -->
    <importRoamList :checkedList="checkedList" ref="daoru" @importList="importList"></importRoamList>
  </div>
</template>
<script>
import imageDataApi from '@/views/js/api/imageDataApi'
import modelList from '../js/model.json';
import Roaming from '../js/roaming'
import cameraUpdater from '../js/cameraUpdater'
import addRecordPanel from './addRecordPanel'
import addOrEditDrawPanel from './addOrEditDrawPanel'
import importRoamList from './importRoamList.vue'

let agCamera = null
let viewer = null
let draw = null
let roam = null
export default {
  props: {
    roamList: {
      type: Array,
      default() {
        return [];
      },
    },
    groupList: {
      type: Array,
      default() {
        return [];
      },
    },
    dirId: {
      type: String
    }
  },
  components: {
    addRecordPanel,
    addOrEditDrawPanel,
    importRoamList
  },
  data() {
    return {
      //点中的当前漫游
      curItem: {
        id: ''
      },
      isContinue: false,

      followedX: -1,
      followedY: 0,
      followedZ: 0,

      //是否列表
      isMulti: true,
      //漫游列表是否锁上
      isListLocked: true,

      //全选
      allChecked: false,
      //半选中
      isIndeterminate: false,
      //选中的数组
      checkedList: [],
    }
  },
  mounted() {
    agCamera = agcim.camera.camera
    viewer = CIM.viewer
    draw = new agcim.interactive.draw(viewer)
    this.isLock = true;
  },
  watch: {
    roamList(val) {
      this.allChecked = false;
      this.checkedList = [];
    }
  },
  methods: {
    // 点击列表 1.重置镜头 2.图标变化  3.执行漫游  4.清除
    playItem(item, index) {
      agCamera.resetCamera(viewer)
      viewer.camera.cancelFlight() // ？
      if (roam) {
        roam.EndRoaming()
        this.stopRoam()
        draw.removeAll()
      }

      if (this.curItem.id == item.id) {
        this.resetPlayIcon();
      } else {
        this.curItem = JSON.parse(JSON.stringify(item));
        this.playRoamItem(item);
      }
    },
    playRoamItem(item) {
      if (item.json.visualAngleType == 'empty') {
        CIM.viewer.scene.requestRenderMode = false
      }
      if (item.json.roamType == 'record') {
        let captureNodes = item.json.captureNodeList
        this.flyToCaptureNode(captureNodes, 0)
      } else {
        this.creatRoaming(item.json)
        this.setFollowed(item.json)
        this.startRoam()
      }
    },
    resetPlayIcon() {
      this.curItem = {
        id: ''
      };
    },

    //定位到节点
    flyToCaptureNode(captureNodes, i) {
      let vm = this
      let captureNode = captureNodes[i]
      let position = captureNode.position
      let posiotion = new Cesium.Cartesian3(position.x, position.y, position.z)
      let heading = captureNode.heading
      let pitch = captureNode.pitch
      let roll = captureNode.roll

      if (i == 0) {
        viewer.scene.camera.setView({
          destination: position,
          orientation: {
            heading: heading,
            pitch: pitch,
            roll: roll,
          },
          duration: 1,
        })
      }

      viewer.camera.flyTo({
        destination: posiotion,
        orientation: {
          heading: heading,
          pitch: pitch,
          roll: roll,
        },
        duration: 2,
        easingFunction: Cesium.EasingFunction.LINEAR_NONE, // 不加执行完一个之后会停顿
        complete: function () {
          if (i < captureNodes.length - 1) {
            vm.flyToCaptureNode(captureNodes, i + 1)
          } else {
            vm.resetPlayIcon();
          }
        },
      })
    },


    // 创建漫游
    creatRoaming(item) {
      let positions = item.positions;
      item.sumDistance = 0
      item.sumTime = 0
      var disArr = [] //点与点之间的距离
      item.sumDistance = agcim.maths.math.getDistances(positions, disArr)
      item.sumTime = item.sumDistance / item.speed
      let modelUrl = this.getModelUrl(item.modelType);

      if (roam) {
        roam.EndRoaming()
        roam = undefined
      }

      if (item.flyheight === 0) {
        item.flyheight = 1
      }
      roam = new Roaming(viewer, {
        time: item.sumTime,
        entityType: item.modelType,
        modelUrl: modelUrl,
        modelScale: this.modelScale,
        Lines: positions,
        flyheight: item.flyheight,
        speed: item.speed,
        disArr: disArr,
        isPathShow: item.isShowRoute,
        angle: item.angle,
        width: item.width,
        isClampToGround: item.isClampToGround,
        cameraHeight: item.cameraHeight
      })
      if (item.cameraHeight) {
        roam.cameraHeight = item.cameraHeight;
      }
    },
    getModelUrl(value) {
      let md = modelList.find(item => {
        return item.value == value
      })
      this.modelScale = 1;
      if (md.scale) this.modelScale = md.scale;
      return md.src;
    },
    // 开始漫游
    startRoam() {
      this.isContinue = true
      if (roam) {
        roam.PauseOrContinue(this.isContinue)
      }
      cameraUpdater.setEnv(this, roam)
      cameraUpdater.preUpdateListener(viewer)
    },
    // 停止漫游
    stopRoam() {
      this.isContinue = false
      if (!roam) {
        return
      }
      roam.PauseOrContinue(this.isContinue)
      agCamera.resetCamera(viewer)
    },
    setFollowed(item) {
      let value = item.visualAngleType;
      if (value == 'empty') {
        //无
        this.isLock = false
        viewer.scene.camera.lookAtTransform(Cesium.Matrix4.IDENTITY)
      } else if (value == 'lockFirst') {
        //锁定第一视角
        this.isLock = true
        var radian = ((2 * Math.PI) / 360) * item.angle
        let x = Math.sin(radian) * item.width
        let y = Math.cos(radian) * item.width
        this.followedX = -x
        this.followedY = 0
        this.followedZ = y
      } else if (value == 'lockGod') {
        //上帝视角
        this.isLock = true
        this.followedX = -1
        this.followedY = 0
        this.followedZ = item.height || 9999
      }
    },
    // 清除
    clearDraw() {
      if (roam) {
        roam.EndRoaming()
      }
      this.stopRoam()
      draw.removeAll()
      this.resetPlayIcon();
    },

    // 编辑列表项
    editItem(item, index) {
      this.clearDraw();
      if (item && item.json.roamType == 'draw') {
        this.$refs.drawBox.onShow(item);
      }
      if (item && item.json.roamType == 'record') {
        this.$refs.recordBox.onShow(item);
      }
    },
    // 添加漫游
    addItem(type) {
      this.clearDraw();
      if(this.groupList.length === 0){
        this.$message({
          message: '请先新建分组',
          type: 'warning'
        });
        return;
      }
      if (type == 'draw') {
        this.$refs.drawBox.onShow(this.dirId);
      }
      if (type == 'record') {
        this.$refs.recordBox.onShow(this.dirId);
      }
    },

    //全选
    changeAllCheck(val) {
      for (let i = 0; i < this.roamList.length; i++) {
        this.roamList[i].checked = this.allChecked;
      }
      if (val) {
        this.isIndeterminate = false;
        this.checkedList = this.roamList;
      } else {
        this.checkedList = [];
      }
    },
    changeCheck() {
      this.checkedList = this.roamList.filter(item => {
        return item.checked
      });
      let len = this.checkedList.length;
      if (0 < len && len < this.roamList.length) {
        this.allChecked = false;
        this.isIndeterminate = true;
      } else {
        if (len == this.roamList.length) {
          this.allChecked = true;
        }else if(len === 0){
          this.allChecked = false;
        }
        this.isIndeterminate = false;
      }
    },
    deleteList() {
      let vm = this;
      let arr = this.checkedList;
      if (arr.length == 0) {
        return this.$message.info("请先勾选");
      }
      this.$confirm('你确定要删除选中的漫游吗？', '漫游删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning',
        center: true,
      }).then(async () => {
        for (let j = 0; j < arr.length; j++) {
          let formData = new FormData()
          formData.append('paramId', arr[j].id)
          let data = await imageDataApi.deleteImageStore(formData)
          if (data.success) {
            if (j == arr.length - 1) {
              vm.updateList();
              vm.allChecked = false;
              vm.isIndeterminate = false;
              vm.checkedList = [];
              vm.$message.success('删除成功')
            }
          } else {
            vm.$message.error(data.message);
          }

        }
      }).catch(() => {
        // vm.$message.success('取消');
      });
    },

    // 删除漫游列表
    deleteItem(id) {
      let vm = this
      let formData = new FormData()
      formData.append('paramId', id)
      let promise = imageDataApi.deleteImageStore(formData)
      promise.then(function (data) {
        if (data.success) {
          vm.updateList();
          vm.allChecked = false;
          vm.checkedList = [];
        } else {
          vm.$message.error(data.message)
        }
      })
      this.clearDraw()
    },
    updateList(id) {
      this.$emit("changeGroup", id);
      this.allChecked = false;
      this.isIndeterminate = false;
      this.roamList.forEach((item) => {
        item.checked = false;
      })
    },
    changeMulit(isMulti) {
      this.isMulti = isMulti
    },
    changeListLocked() {
      this.isListLocked = !this.isListLocked;
      this.isIndeterminate = false;
      this.allChecked = false;
      this.roamList.forEach((item) => {
        item.checked = false;
      })
    },
    dragstart(value) {
      if (this.isListLocked){
        return;
      }
      this.oldData = value;
    },
    dragenter(value) {
      if (this.isListLocked){
        return;
      }
      this.newData = value
    },
    async dragend(value) {
      if (this.isListLocked){
        return;
      }
      if (this.oldData !== this.newData) {
        let oldIndex = this.roamList.indexOf(this.oldData)
        let newIndex = this.roamList.indexOf(this.newData)
        let newItems = [...this.roamList]
        newItems.splice(oldIndex, 1)
        newItems.splice(newIndex, 0, this.oldData)

        let arr = [];
        let max = oldIndex > newIndex ? oldIndex : newIndex;
        let min = oldIndex > newIndex ? newIndex : oldIndex;

        for (let i = min; i < max + 1; i++) {
          arr.push(newItems[i].id)
        }

        let res = await imageDataApi.dragSort(arr);
        if (res.success) {
          this.$emit("changeGroup");
          this.newData.id = '';
        }
      }

    },
    daochu() {
      if (!this.checkedList.length) return;
      let arr = this.checkedList.map(item => {
        return JSON.parse(JSON.stringify(item.json))
      })
      arr = JSON.stringify(arr)
      let funDownload = function (content, filename) {
        let elelink = document.createElement('a');
        elelink.download = filename;
        elelink.style.display = 'none';
        let blob = new Blob([content], {type: "application/json"});
        elelink.href = URL.createObjectURL(blob);
        document.body.appendChild(elelink);
        elelink.click();
        document.body.removeChild(elelink);
      }
      let title = '漫游文件'
      if (this.checkedList.length == 1) {
        title = this.checkedList[0].name;
      }
      funDownload(arr, title);
    },
    daoru() {
      this.$refs.daoru.onShow();
    },
    importList(roamFile) {
      let vm = this;
      for (let i = 0; i < roamFile.length; i++) {
        let params = {
          imageStoreDirId: this.dirId,
          imageStoreName: roamFile[i].name,
          imageStoreInformation: JSON.stringify(roamFile[i]),
        };
        let promisett = imageDataApi.saveImageStore(params);
        promisett.then(
            function (data) {
              if (data.success) {
                if (i == roamFile.length - 1) {
                  vm.$message.success(data.message);
                  vm.updateList();
                  this.$refs.daoru.clearUpload();
                }
              }
            }.bind(this)
        );
      }
    }
  },
}
</script>

<style scoped src="../css/style.css"></style>
<style lang="less" scoped>
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;

  .menu {
    font-size: 0;
  }

  i {
    cursor: pointer;
  }

  .el-checkbox {
    color: #fff;
    margin-right: 8px;
  }
}

.border-box {
  display: inline-block;
  border: 1px solid #1e90ff;
  height: 32px;
  vertical-align: top;
  border-radius: 4px;
  margin-right: 8px;

  i {
    vertical-align: middle;
  }

  span {
    display: inline-block;
    height: 30px;
    line-height: 30px;
    width: 32px;
    text-align: center;
  }

  span.active {
    background: #1e90ff;
  }
}

.icon-draw {
  margin-left: 8px;
}

.right-list-box {
  min-height: 360px;

  .empty {
    text-align: center;
    padding: 50px 0;
    color: rgba(255, 255, 255, 0.5);
  }

  .icon-delete1 {
    display: none;
  }

  .border-daochu {
    display: none;
  }

  .border-daoru {
    display: inline-block;
  }

  .iconPlayer {
    position: absolute;
    top: calc(50% - 30px);
    left: calc(50% - 20px);
    width: 36px;
    height: 36px;
  }

  .btm {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    max-height: 400px;
    width: 370px;
    padding: 0 20px;

    .drag-move {
      transition: transform 0.5s;
    }

    .el-checkbox {
      display: none;
    }
  }

  .picture-item {
    width: 48%;
    text-align: center;
    height: 122px;
    color: #ffffff;
    cursor: pointer;
    position: relative;
    margin-bottom: 16px;

    .name {
      position: absolute;
      bottom: 0px;
      width: 100%;
      height: 24px;
      line-height: 24px;
      text-align: center;
      color: #ffffff;
      background-color: rgba(34, 34, 34, 0.6);
      font-size: 14px;
      font-weight: 400;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      word-break: break-all;
    }

    .el-checkbox {
      display: none;
      position: absolute;
      top: 4px;
      left: 4px;
    }

    .ibox {
      display: none;
      position: absolute;
      top: calc(50% - 10px);
      left: 50%;
      color: #fff;
      height: 24px;
      width: 24px;
      border-radius: 50%;
      text-align: center;
      margin-top: -12px;
    }

    &:hover .ibox {
      display: inline-block;
    }

    .ibox.edit {
      margin-left: -55px;
      background: #1e90ff;
    }

    .ibox.delete {
      margin-left: 27px;
      background: #fb4e60;
    }

    .icon {
      font-size: 16px;
      line-height: 24px;
      vertical-align: text-bottom;
      display: inline-block;
      width: 24px;
      height: 24px;
    }

    .draw-mark {
      width: 20px;
      height: 20px;
      display: inline-block;
      position: absolute;
      top: 0;
      right: 0;
      background: #000;
      border-bottom-left-radius: 4px;
      text-align: center;
    }

    img {
      width: 100%;
      height: 100%;
    }
  }

  .thumb-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 336px;
    padding: 3px 12px;
    margin-bottom: 12px;
    border-radius: 4px;
    background: rgba(255, 255, 255, 0.15);
    box-sizing: border-box;
    border: 1px solid rgba(255, 255, 255, 0.15);
    height: 70px;

    &:hover {
      border: 1px solid #fed430;
      cursor: pointer;
    }

    > div {
      display: inline-flex;
    }

    .el-checkbox {
      margin-right: 8px;
      line-height: 44px;
    }

    img {
      margin: 0 12px;
      width: 44px;
      height: 44px;
    }

    .rt i {
      margin: 0 4px;
    }

    .record-index {
      line-height: 44px;
    }

    .record-name {
      display: inline-block;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      word-break: break-all;
      width: 140px;
      line-height: 44px;
    }
  }

  &.unlock-list-active {

    .icon-draw,
    .icon-record {
      display: none;
    }

    .icon-delete1 {
      display: inline-block;
    }

    .border-daochu {
      display: inline-block;
    }

    .border-daoru {
      display: none;
    }

    .btm .el-checkbox {
      display: inline-block;
    }
  }
}

::v-deep .is-disabled .el-checkbox__inner,
::v-deep .el-checkbox__inner {
  background: transparent;
}

::v-deep .el-checkbox__label {
  color: #fff;
}
</style>